package com.eunion.boot.security;

import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Spring security工具类.
 * SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
 * WebAuthenticationDetails details = (WebAuthenticationDetails) securityContextImpl.getAuthentication().getDetails();
 * 
 * @since 2017年1月1日
 */
public class SpringSecurityUtil {

	/**
	 * 获取当前登录用户名，如果没有，就返回null.
	 * @return 如果没有可能返回null.
	 */
	public static String getCurrentUserName() {
		if (!isClearContext()) {
			Object at = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if (at != null && at instanceof SysUserDetails) {
				SysUserDetails userDetails = (SysUserDetails) at;
				//过滤状态小于0的用户
				if(userDetails.getStatus()<=0){
					return null;
				}
				return userDetails.getUsername();
			}
		}
		return null;
	}

	/**
	 * 判斷是否还有登陆信息.
	 * @return true如果有.
	 */
	private static boolean isClearContext() {
		return (SecurityContextHolder.getContext() == null || SecurityContextHolder.getContext().getAuthentication() == null);
	}

	/**
	 * 清理用户登录信息.
	 */
	public static String invalidateUser() {
		SecurityContextHolder.clearContext();
		if (!isClearContext()) {
			Object at = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if (at != null && at instanceof SysUserDetails) {
				SysUserDetails userDetails = (SysUserDetails) at;
				return userDetails.getUsername();
			}
		}
		return null;
	}

	/**
	 * 获取当前登录用户名，如果没有，就返回null.
	 * @return 如果没有可能返回null.
	 */
	public static SysUserDetails getCurrentUser() {
		if (!isClearContext()) {
			Object at = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if (at != null) {
				SysUserDetails userDetails = (SysUserDetails) at;
				return userDetails;
			}
		}
		return null;
	}

}
